package com.photopicker.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.google.common.base.Objects;

import java.util.List;

/**
 * Created by Gary on 2016/4/15.
 */
public abstract class DefaultBaseAdapter<T> extends BaseAdapter implements IAdapter<T> {

    protected Context context;
    private final LayoutInflater mLayoutInflater;

    private final int mViewLayoutId;

    private List<T> mItems;

    public DefaultBaseAdapter(Context context, int viewLayoutId) {
        this.context = context;
        mLayoutInflater = LayoutInflater.from(context);
        mViewLayoutId = viewLayoutId;
    }

    public DefaultBaseAdapter(Context context, List<T> mItems) {
        this.context = context;
        mLayoutInflater = LayoutInflater.from(context);
        mViewLayoutId = 0;
        this.mItems = mItems;
    }

    public void setItems(List<T> items) {
        if (!Objects.equal(items, mItems)) {
            mItems = items;
            notifyDataSetChanged();
        }
    }

    @Override
    public void setList(List<T> items) {
        mItems = items;
    }

    public Context getContext() {
        return this.context;
    }

    public LayoutInflater getLayoutInflater() {
        return mLayoutInflater;
    }

    public void setItemsNoCompare(List<T> items) {
        mItems = items;
        notifyDataSetChanged();
    }

    public List<T> getmItems() {
        return mItems;
    }

    public void setmItems(List<T> mItems) {
        this.mItems = mItems;
    }

    @Override
    public int getCount() {
        return mItems != null ? mItems.size() : 0;
    }

    @Override
    public T getItem(int position) {
        return mItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        Object holder;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(mViewLayoutId, viewGroup, false);

            holder = createViewHolderAndFindViewById(position, convertView);
            convertView.setTag(holder);
        } else {
            holder = convertView.getTag();
        }
        final T item = getItem(position);

        bindView(position, holder, item);

        return convertView;
    }

    protected void bindView(int position, Object view, T item) {

    }

    protected Object createViewHolderAndFindViewById(int position, View convertView) {
        return null;
    }

}
